import axios from "axios"
import { ElMessage } from "element-plus"

const API = axios.create({
  baseUrl: import.meta.env.VITE_BASE_URL, //请求后端数据的基本地址，自定义
  timeout: 3000, //请求超时设置，单位ms
  headers: {
    "Content-Type": "application/json; charset=utf-8",
  },
})
// 请求拦截器
API.interceptors.request.use(config => {
  config.headers = config.headers || {}
  if (localStorage.getItem("token")) {
    config.headers.Authorization = localStorage.getItem("token") || ""
  }
  return config
})
// 响应拦截器
const ResponseProcessing = error => {
  if (error.response) {
    if (error.response.status == 401) {
      window.location.href='login'
      ElMessage({
        message: "资源没有访问权限！",
        type: "warning",
      })
    } else if (error.response.status == 404) {
      ElMessage({
        message: "接口不存在，请检查接口地址是否正确！",
        type: "warning",
      })
    } else if (error.response.status == 500) {
      ElMessage({
        message: "内部服务器错误，请联系系统管理员！",
        type: "warning",
      })
    } else {
      return Promise.reject(error.response.data)
    }
  } else {
    ElMessage.error("遇到跨域错误，请设置代理或者修改后端允许跨域访问！")
  }
}
API.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    ResponseProcessing(error)
  }
)

export default API
